/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pub;

import Utils.Static;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.ProductModel;

/**
 *
 * @author user
 */
public class cart extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession(true);
            if (session.getAttribute(Static.categories) == null) {
                response.sendRedirect("load");
                return;
            }
            ArrayList<String> script = new ArrayList<String>();
            script.add("<script type=\"text/javascript\" src=\"jscripts/cart.js\"></script>");
            session.setAttribute(Static.java_script, script);

            String action = request.getParameter(Static.action);
            if (action == null) {
                Index(request, response);
            } else if (action.compareTo("delete") == 0) {
                Delete(request, response);
            } else if (action.compareTo("add") == 0) {
                Add(request, response);
            } else if (action.compareTo("edit") == 0) {
                Edit(request, response);
            } else if (action.compareTo("clear") == 0) {
                Clear(request, response);
            } else {
                Index(request, response);
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void Index(HttpServletRequest request, HttpServletResponse response) {
        try {
            getServletContext().getRequestDispatcher("/pub/cart/index.jsp").forward(request, response);
        } catch (Exception ex) {
        }
    }

    public void Add(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            PrintWriter out = response.getWriter();
            int id = Integer.parseInt(request.getParameter(Static.id));
            ProductModel productModel = new ProductModel();
            HashMap product = productModel.GetProduct(id);
            ArrayList cart;
            float quantity = 1;

            if (session.getAttribute(Static.cart) != null) {
                cart = (ArrayList) session.getAttribute(Static.cart);
            } else {
                cart = new ArrayList();
            }

            if (request.getParameter(Static.quantity) != null)//vine din products_details
            {
                quantity = Float.parseFloat(request.getParameter(Static.quantity).toString());
                //throw new Exception ( "Cantitatea trebuie sa contina numai cifre" );

                if (quantity < 0) {
                    throw new Exception("Cantitatea trebuie sa fie pozitiva");
                }
            }

            cart = Search(product, cart, quantity);
            session.setAttribute(Static.cart, cart);

            if (request.getParameter(Static.quantity) != null) {
                response.sendRedirect("products");
                return;
            }

            out.println(cart.size());
        } catch (Exception ex) {
            String error = ex.getMessage();
        }
    }

    public void Edit(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);

            int id = Integer.parseInt(request.getParameter(Static.id));
            float quantity = Integer.parseInt(request.getParameter(Static.quantity));

            ArrayList cart = (ArrayList) session.getAttribute(Static.cart);
            int size = cart.size();

            for (int i = 0; i < size; i++) {
                if (Integer.parseInt(((HashMap) cart.get(i)).get("ProductID").toString()) == id) {
                    ((HashMap) cart.get(i)).put("Quantity", quantity);
                }
            }
            session.setAttribute(Static.cart, cart);
            PrintWriter out = response.getWriter();
            out.print("OK");

        } catch (Exception ex) {
        }
    }

    public void Delete(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            int id = Integer.parseInt(request.getParameter(Static.id));

            ArrayList cart = (ArrayList) session.getAttribute(Static.cart);
            int size = cart.size();

            for (int i = 0; i < size; i++) {
                HashMap p = (HashMap) cart.get(i);
                if (Integer.parseInt(p.get("ProductID").toString()) == id) {
                    cart.remove(i);
                }
            }
            session.setAttribute(Static.cart, cart);
        } catch (Exception ex) {
        }
    }

    public void Clear(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            session.setAttribute(Static.cart, null);
            response.sendRedirect("cart");
        } catch (Exception ex) {
        }
    }

    private ArrayList Search(HashMap product, ArrayList cart, float quantity) {
        try {
            int size = cart.size();
            int id = Integer.parseInt(product.get("ProductID").toString());
            boolean inList = false;
            for (int i = 0; i < size; i++) {
                if (Integer.parseInt(((HashMap) cart.get(i)).get("ProductID").toString()) == id) {
                    inList = true;
                    float t_quantity = (Float) ((HashMap) cart.get(i)).get("Quantity") + quantity;
                    ((HashMap) cart.get(i)).put("Quantity", t_quantity);
                }
            }
            if (!inList) {
                product.put("Quantity", quantity);
                cart.add(product);
            }

            return cart;
        } catch (Exception ex) {
            return null;
        }
    }
}
